package com.jakewharton.rxbinding4.component;

import static com.jakewharton.rxbinding4.internal.Preconditions.checkMainThread;

import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.functions.Predicate;
import io.reactivex.rxjava3.openharmony.MainThreadDisposable;
import ohos.agp.components.Component;
import ohos.agp.components.ListContainer;

final class ListContainerItemLongClickedObservable extends Observable<ListContainerItemEvent> {
    private final ListContainer view;
    private final Predicate<? super ListContainerItemEvent> handled;

    ListContainerItemLongClickedObservable(ListContainer view, Predicate<? super ListContainerItemEvent> handled) {
        this.view = view;
        this.handled = handled;
    }

    @Override
    protected void subscribeActual(Observer<? super ListContainerItemEvent> observer) {
        if (!checkMainThread(observer)) {
            return;
        }
        Listener listener = new Listener(view, handled, observer);
        observer.onSubscribe(listener);
        view.setItemLongClickedListener(listener);
    }

    static final class Listener extends MainThreadDisposable implements ListContainer.ItemLongClickedListener {
        private final ListContainer view;
        private final Predicate<? super ListContainerItemEvent> handled;
        private final Observer<? super ListContainerItemEvent> observer;

        Listener(
                ListContainer view,
                Predicate<? super ListContainerItemEvent> handled,
                Observer<? super ListContainerItemEvent> observer) {
            this.view = view;
            this.handled = handled;
            this.observer = observer;
        }

        @Override
        protected void onDispose() {
            view.setItemLongClickedListener(null);
        }

        @Override
        public boolean onItemLongClicked(ListContainer parent, Component component, int position, long id) {
            if (!isDisposed()) {
                try {
                    ListContainerItemEvent event = ListContainerItemEvent.create(parent, component, position, id);
                    if (handled.test(event)) {
                        observer.onNext(event);
                        return true;
                    }
                } catch (Throwable e) {
                    observer.onError(e);
                    dispose();
                }
            }
            return false;
        }
    }
}
